package com.example.demo.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author yzd
 */
@Service
public class LdapSelectService {
	@Autowired
	private LdapTemplate ldapTemplate;
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	/**
	 * 获取子节点 若获取所有子节点时，只需判断是否是ou还是cn就可以了
	 * @param rdn
	 * @return
	 */
	public List<String> findChild(String rdn) {
		List<String> res = ldapTemplate.list(rdn);
		logger.info(this.getDnOfGroup(rdn) + "");
		logger.info(this.getDnOfPerson(rdn) + "");
		return res;
	}

	/**
	 * 直接拼接时newContactDN.add("cn", "aa1，ou=Group")多个转义字符，没有删除掉
	 * 得到person的dn
	 * @param cn
	 * @return
	 */
	//
	public DistinguishedName getDnOfPerson(String cn) {
		// 得到根目录，也就是配置文件中配置的ldap的根目录
		DistinguishedName newContactDN = new DistinguishedName();
		// 添加cn，即使得该条记录的dn为"cn=cn,根目录",例如"cn=abc,dc=testdc,dc=com"
		DistinguishedName name1 = new DistinguishedName("cn=" + cn);
		name1.append(newContactDN);
		return name1;
	}

	/**
	 * 得到ou的dn
	 * @param ou
	 * @return
	 */
	public DistinguishedName getDnOfGroup(String ou) {
		DistinguishedName newContactDN = new DistinguishedName();
		DistinguishedName name1 = new DistinguishedName("ou=" + ou);
		name1.append(newContactDN);
		return name1;
	}
}
